package es.esi.gemde.methodmanager.service.handlers;

import java.io.File;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;

import es.esi.gemde.core.utils.GEMDEUtils;
import es.esi.gemde.methodmanager.CommandConstants;

public class OpenEditorCommandHandler extends AbstractHandler {
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String editorID = event.getParameter(CommandConstants.EDITORID_PARAM_ID);
		
		if (editorID == null) {
			throw new ExecutionException("No editor ID was provided. Cannot open the editor.");
		}
		
		String openedFile = event.getParameter(CommandConstants.FILE_PARAM_ID);
		
		// Find the editor in the registry
		IEditorDescriptor editor = PlatformUI.getWorkbench().getEditorRegistry().findEditor(editorID);
		if (editor == null) {
			throw new ExecutionException("No editor was found with the provided ID. Cannot open editor.");
		}
		
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		
		if (openedFile == null) {
			throw new ExecutionException("No file was provided. Failed to initialize the editor.");
		}
		else {
			File f = new File(openedFile);

			if (!f.exists() || f.isDirectory()) {
				throw new ExecutionException("Provided input file is not valid. Failed to open the editor.");
			}

			try {

				if (GEMDEUtils.isFileInWorkspace(f)) {
					IFile file = (IFile) GEMDEUtils.toWorkspaceFile(f);
					page.openEditor(new FileEditorInput(file), editorID);
				}
				else {
					// Try to open external file
					IFileStore fileStore = EFS.getLocalFileSystem().getStore(f.toURI());
					IDE.openEditorOnFileStore(page, fileStore);
				}
			}
			catch (PartInitException e) {
				throw new ExecutionException("Failed to initialize the editor.", e);
			}
		}
		
		return null;
	}

}